import {
    Config
} from './config'
import {
    Token
} from './token'
import Toast from '@vant/weapp/toast/toast'
import Dialog from '@vant/weapp/dialog/dialog'
import QQMapWX from './qqmap-wx-jssdk'
const token = new Token()
const qqmapsdk = new QQMapWX({
    key: Config.lbsKey
})
const subscribeWaitAudit = Config.tmplIds.subscribeWaitAudit
const subscribeCanceled = Config.tmplIds.subscribeCanceled
const auditNotice = Config.tmplIds.auditNotice
const subscribeComplete = Config.tmplIds.subscribeComplete
class Base {
    constructor() {}

    /**
     * GET类型的网络请求
     */
    getRequest(url, data) {
        return this.requestAll(url, data, 'GET')
    }

    /**
     * POST类型的网络请求
     */
    postRequest(url, data) {
        return this.requestAll(url, data, 'POST')
    }

    /**
     * PUT类型的网络请求
     */
    putRequest(url, data) {
        return this.requestAll(url, data, 'PUT')
    }

    /**
     * DELETE类型的网络请求
     */
    deleteRequest(url, data) {
        return this.requestAll(url, data, 'DELETE')
    }

    /**
     * 网络请求
     */
    requestAll(url, data, method) {
        return new Promise((resolve, reject) => {
            wx.request({
                url: Config.baseUrl + url,
                data: data,
                header: {
                    token: wx.getStorageSync('token')
                },
                method: method,
                success: (res) => {
                    // 判断以2（2xx)开头的状态码为正确
                    // 服务端业务处理正常结束
                    let code = res.statusCode.toString()
                    let startChar = code.charAt(0)
                    if (startChar == '2') {
                        resolve(res)
                    } else {
                        // 401则重新登录
                        if (code == '401') {
                            // 401处理逻辑
                            token.verify()
                            wx.showToast({
                                title: '登录过期，已重新登录，请重试',
                                icon: 'none',
                                duration: 2000
                            })
                        } else {
                            //其它错误，提示用户错误信息
                            let message = res.data.message,
                                title = message ? message.split(',')[0] : `服务器内部错误, ${code}`
                            wx.showToast({
                                title: title,
                                icon: 'none',
                                duration: 2000
                            })
                            // reject(res)
                        }
                    }
                },
                fail: (err) => {
                    wx.showToast({
                        title: "网络请求失败，请重试",
                        icon: 'none'
                    })
                    // reject(err)
                }
            })
        })
    }

    /**
     * 调用微信支付接口
     * @param {*} res
     */
    pay(res) {
        return new Promise((resolve, reject) => {
            wx.requestPayment({
                timeStamp: res.data.timeStamp + "",
                nonceStr: res.data.nonceStr,
                package: res.data.package,
                signType: res.data.signType,
                paySign: res.data.paySign,
                success: (res) => {
                    resolve(res)
                },
                fail: (err) => {
                    reject(err)
                }
            })
        })
    }


    /**
     * 从本地相册选择图片或使用相机拍照
     * @param {*} count 最多可以选择的图片张数
     * @param {*} sizeType 所选的图片的尺寸, 默认['original', 'compressed']
     * @param {*} sourceType 选择图片的来源, 默认['album', 'camera']
     */
    chooseImage(count = 1, sizeType = 'compressed', sourceType = ['album', 'camera']) {
        return new Promise((resolve, reject) => {
            wx.chooseImage({
                count: count, // 默认9
                sizeType: sizeType,
                sourceType: sourceType,
                success: (res) => {
                    wx.showLoading({
                        title: "图片上传中"
                    })
                    resolve(res.tempFilePaths)
                },
                fail: (err) => {
                    reject(err)
                }
            })
        })
    }

    /**
     * 将本地资源上传到服务器
     * @param {*} url 服务器地址
     * @param {*} filePath 要上传文件资源的路径 (本地路径)
     * @param {*} name 文件名称
     * @param {*} formData 额外参数
     */
    uploadFile(url, filePath, name = 'image', formData = {}) {
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url: url,
                filePath: filePath[0],
                name: name,
                formData: formData,
                success: (res) => {
                    wx.showLoading({
                        title: "处理中，请稍后"
                    })
                    resolve(res)
                },
                fail: (err) => {
                    reject(err)
                }
            })
        })
    }

    /**
     * 授权位置信息
     */
    authLocation() {
        return new Promise((resolve) => {
            // 是否授权
            wx.getSetting({
                success: (res) => {
                    // 没有位置权限
                    if (!res.authSetting['scope.userLocation']) {
                        // 主动向用户获取位置权限
                        wx.authorize({
                            scope: 'scope.userLocation',
                            success: () => {
                                resolve()
                            },
                            fail: () => {
                                Dialog.alert({
                                    title: '提示',
                                    message: '使用需开启定位权限，请授权',
                                }).then(() => {
                                    wx.openSetting()
                                })
                            }
                        })
                    } else {
                        resolve()
                    }
                }
            })
        })
    }

    /**
     * 获取用户经纬度
     */
    getUserLocation() {
        return new Promise(function (resolve, reject) {
            wx.getLocation({
                type: 'gcj02',
                success: (res) => {
                    resolve(res)
                },
                fail: () => {
                    reject("系统异常，请重试！")
                }
            })
        })
    }

    /**
     * 逆地址解析，根据经纬度获取地址信息
     * @param {*} lat 纬度
     * @param {*} lng 经度
     */
    getAddress(lat, lng) {
        return new Promise((resolve, reject) => {
            qqmapsdk.reverseGeocoder({
                location: `${lat},${lng}`,
                success: (res) => {
                    resolve(res)
                },
                fail: (err) => {
                    reject(err)
                }
            })
        })
    }

    /**
     * 发送订阅消息
     * @param {*} order_id 订单ID
     * @param {*} type 订阅消息类型
     */
    sendSubscribeMessage(order_id, type) {
        let that = this,
            tmplId = '',
            tmplIds = [subscribeComplete, auditNotice, subscribeWaitAudit]
        switch (type) {
            case 'subscribeComplete':
                tmplId = subscribeComplete
                break
            case 'failed':
                tmplId = auditNotice
                break
            case 'subscribeWaitAudit':
                tmplId = subscribeWaitAudit
                break
        }
        wx.getSetting({
            withSubscriptions: true,
            success: (res) => {
                const mainSwitch = res.subscriptionsSetting.mainSwitch,
                    itemSettings = res.subscriptionsSetting.itemSettings
                if (mainSwitch && (!itemSettings || (itemSettings && 'accept' == itemSettings[tmplId]))) {
                    wx.requestSubscribeMessage({
                        tmplIds: tmplIds,
                        complete: (res) => {
                            if ('accept' == res[tmplId]) {
                                let param = {
                                    type: type,
                                    order_id: order_id,
                                }
                                that.postRequest(`car/send`, param)
                            }
                        }
                    })
                }
            }
        })
    }

    /**
     * 获得元素上的绑定的值
     * @param {*} event 要获取的元素
     * @param {*} key 要获取的值
     */
    getDataSet(event, key) {
        return event.currentTarget.dataset[key]
    }

    /**
     * 设置缓存和过期时间
     * @param {*} title 缓存名称
     * @param {*} value 缓存内容
     * @param {*} expirationTime 缓存时间
     */
    setStorage(title, value, expirationTime = 7200000) {
        let expire = Date.parse(new Date()) + expirationTime
        wx.setStorageSync(title, value)
        wx.setStorageSync(`${title}_expire`, expire)
    }

    /**
     * 获取缓存数据
     * @param {*} title 缓存名称
     */
    getStorage(title) {
        let that = this,
            data = wx.getStorageSync(title), // 缓存数据
            expire = wx.getStorageSync(`${title}_expire`), // 过期时间戳
            timestamp = Date.parse(new Date()) // 当前时间戳
        if (data && expire > timestamp) {
            wx.removeStorageSync({
                key: title,
                success: () => {
                    that.setStorage(title, data)
                }
            })
        }
        return data
    }

    /**
     * 移除缓存
     * @param {*} title
     */
    removeStorage(title) {
        wx.removeStorageSync(title)
        wx.removeStorageSync(`${title}_expire`)
    }

    /**
     * 获取上一页
     */
    getPrevPage() {
        let pages = getCurrentPages(), // 获取加载的页面
            prevPage = pages[pages.length - 2] // 获取上一页
        return prevPage
    }

    /**
     * 获取当前页参数的拼接字符串
     */
    getCurrentPageOptions() {
        let pages = getCurrentPages(), // 获取加载的页面
            currentPage = pages[pages.length - 1], // 获取当前页面的对象
            options = currentPage.options, // 当前页面参数
            param = ''
        if (options) {
            for (let key in options) {
                if (options.hasOwnProperty(key)) {
                    let value = options[key]
                    param = `${param}${key}=${value}&`
                }
            }
            param = param.substr(0, param.length - 1)
        }
        return param
    }

    /**
     * 获取当前完整日期, 如: 2020-02-02
     * @param {*} time 时间戳
     */
    getFullDate(time = '') {
        let date = time ? new Date(time) : new Date(),
            year = date.getFullYear(),
            month = date.getMonth() + 1,
            day = date.getDate()
        month = ('0' + month).substr(-2)
        day = ('0' + day).substr(-2)
        return year + '-' + month + '-' + day
    }
}

export {
    Base
}